# myproject/scripts/import_projects.py
import os
import csv
from datetime import datetime
import django
import sys

# 设置Django环境
# 修改BASE_DIR的计算方式（减少一层目录）
BASE_DIR = os.path.dirname(os.path.abspath(__file__))  # 当前脚本的绝对路径
for _ in range(2):  # 向上回退两级目录
    BASE_DIR = os.path.dirname(BASE_DIR)
sys.path.append(BASE_DIR)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")
django.setup()

from django.contrib.auth.models import User
from app01.models import Project

def import_projects(csv_path):
    # 创建日志目录
    log_dir = os.path.join(os.path.dirname(csv_path), "import_logs")
    os.makedirs(log_dir, exist_ok=True)
    
    # 初始化统计
    stats = {
        'total': 0,
        'success': 0,
        'errors': [],
        'error_file': os.path.join(log_dir, "errors.csv")
    }

    with open(csv_path, 'r', encoding='utf-8') as csv_file, \
         open(stats['error_file'], 'w', encoding='utf-8', newline='') as error_file:

        reader = csv.DictReader(csv_file)
        error_writer = csv.writer(error_file)
        error_writer.writerow(['行号', '名称', '错误信息'] + reader.fieldnames)

        for i, row in enumerate(reader, 1):
            stats['total'] += 1
            try:
                # 验证必须字段
                if not row.get('name'):
                    raise ValueError("名称不能为空")

                # 处理创建者外键
                creator = User.objects.get(id=row['creator']) if row.get('creator') else None

                # 创建项目对象
                project = Project(
                    name=row['name'],
                    color=int(row['color']) if row.get('color') else 1,
                    desc=row.get('desc', '') or None,
                    use_space=int(row.get('use_space', 0)),
                    star=row.get('star', 'False').lower() == 'true',
                    join_count=int(row.get('join_count', 1)),
                    creator=creator,
                    create_datetime=datetime.strptime(row['create_datetime'], '%Y-%m-%d %H:%M:%S') 
                        if row.get('create_datetime') else datetime.now()
                )

                # 全字段验证
                project.full_clean()
                project.save()

                stats['success'] += 1

            except Exception as e:
                error_msg = f"第{i}行错误: {str(e)}"
                stats['errors'].append(error_msg)
                error_writer.writerow([i, row.get('name'), str(e)] + list(row.values()))
                print(f"❌ {error_msg}")

    # 打印统计结果
    print(f"\n导入完成 ✅")
    print(f"总记录数: {stats['total']}")
    print(f"成功导入: {stats['success']}")
    print(f"失败记录: {len(stats['errors'])}")
    if stats['errors']:
        print(f"错误日志已保存至: {stats['error_file']}")

if __name__ == "__main__":
    csv_path = os.path.join(os.path.dirname(__file__), "lines.csv")
    import_projects(csv_path)